#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "../common/util.hpp"
#include "../common/log.hpp"

namespace rs_compile
{
    using namespace rs_util;
    using namespace rs_log;

    class Compiler
    {

    public:
        Compiler()
        {
        }
        ~Compiler()
        {
        }

        static bool Compile(const std::string &file_name)
        {
            pid_t rid = fork();
            if (rid < 0)
            {
                // 创建子进程失败
                LOG(ERROR)<<"创建子进程失败！"<<"\n";
                return false;
            }
            else if (rid == 0)
            {
                int _stderr = open(PathUtil::ErrFile(file_name).c_str(),O_CREAT|O_WRONLY,0644);
                if(_stderr < 0)
                {
                    LOG(WARNING)<<"没有形成stderr文件！"<<"\n";
                    exit(1);
                }

                dup2(_stderr,2);

                execlp("g++","g++", "-o", PathUtil::ExeFile(file_name).c_str(),\
                           PathUtil::SrcFile(file_name).c_str(),"-D","COMPILER_ONLINE", "-std=c++11",nullptr);
                LOG(ERROR)<<"启动g++失败！"<<"\n";
                exit(2);
            }
            else
            {
                pid_t wpid = waitpid(rid, nullptr, 0);
                if (FileUtil::IsFileExist(PathUtil::ExeFile(file_name)))
                {
                    LOG(INFO)<<"编译成功！"<<"\n";
                    return true;
                }
                LOG(ERROR)<<"编译失败没有形成可执行文件！"<<"\n";
                return false;
            }
        }
    };
}
